/*
 * 文件名：SystemController.java
 * 版权：Copyright by will_awoke
 * 描述：
 * 修改人：will_awoke
 * 修改时间：2014-8-18
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */
package com.qbgs.rbac.controller;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qbgs.constant.GlobalConstant;
import com.qbgs.rbac.bean.SysMenu;
import com.qbgs.rbac.service.SystemService;


/**
 * 系统级控制器，包括登录、退出、验证码等 
 * Returning cached instance of singleton bean 'systemController'
 * 
 * @author lyh
 * @version 2014-8-18
 * @see SystemController
 * @since
 */
@Controller
public class SystemController
{

    @Autowired
    private SystemService systemService;

    /**
     * 由于welcome-file也进行了dispatcher，所以此处需要配置 return 后跟跳转的视图名 index.jsp
     */
    @RequestMapping(value = "index.as")
    public String index(HttpServletRequest request)
        throws Exception
    {
        return "index";
    }

    /**
     * 跳转到登录页面 return 后跟跳转的视图名login/user_login.jsp
     */
    @RequestMapping(value = "login/toLogin.as")
    public String toLogin(HttpServletRequest request)
        throws Exception
    {
        return "login/user_login";
    }

    /**
     * 异步获取当前用户的导航菜单（此方法被filter拦截）
     * 
     * @param request
     * @param response
     * @throws Exception
     * @see
     */
    @RequestMapping(value = "login/navi.do")
    @ResponseBody
    public List<SysMenu> navi(HttpServletRequest request, HttpServletResponse response)
    {
        //当前session中登录用户
        String loginName = (String)(request.getSession().getAttribute(GlobalConstant.AUTH_SESSION_USERNAME_KEY));
        List<SysMenu> list = systemService.queryNaviJsonByUser(loginName);

        //返回List<SysMenu>，jackson成json至页面
        return list;
    }

    /**
     * 用户登录方法
     * 
     * @return
     * @see
     */
    @RequestMapping(value = "login/userLogin.as")
    public String userLogin(HttpServletRequest request, HttpServletResponse response)
        throws Exception
    {
        // 防止地址栏直接回车login/userLogin.as
        // 获取session中当前用户名，如果已经登录了就跳转到main首页
        String loginName = (String)request.getSession().getAttribute(
            GlobalConstant.AUTH_SESSION_USERNAME_KEY);
        if (!StringUtils.isEmpty(loginName))
        {
            return "main/main";
        }

        // 获得session中验证码
        String validateCodePic = (String)(request.getSession().getAttribute("validateCode"));

        String validateCode = request.getParameter("validateCode");
        String name = request.getParameter("name");
        String passwd = request.getParameter("passwd");

        // 验证码是否输入为空
        if (StringUtils.isEmpty(validateCode))
        {
            request.setAttribute("name", name);
            request.setAttribute("passwd", passwd);
            request.setAttribute("loginError", GlobalConstant.SECURITYCODE_NULL);

            // return "forward:/hello";
            // return "redirect:/hello.do";

            // equals to forward to viewJsp , shared the same req and rsp.
            return "login/user_login";
        }
        // 验证码不相同
        else if (!StringUtils.equalsIgnoreCase(validateCode, validateCodePic))
        {
            request.setAttribute("name", name);
            request.setAttribute("passwd", passwd);
            request.setAttribute("loginError", GlobalConstant.SECURITYCODE_ERROR);

            return "login/user_login";
        }
        // 调用验证方法
        else
        {
            // 登录验证通过
            if (systemService.isExists(name, passwd))
            {
                // 当前登录用户存入session
                request.getSession().setAttribute(GlobalConstant.AUTH_SESSION_USERNAME_KEY, name);

                // 采用异步加载模式asyn，另请参见：navi()
                return "main/main";
            }
            // 验证不通过
            else
            {
                request.setAttribute("name", name);
                request.setAttribute("passwd", passwd);
                request.setAttribute("loginError", GlobalConstant.PASSWD_NAME_ERROR);

                return "login/user_login";
            }
        }
    }

    /**
     * 跳转到欢迎首页
     * 
     * @return
     * @see
     */
    @RequestMapping(value = "/login/toWelcome.as")
    public String toWelcome()
        throws Exception
    {
        return "main/welcome";
    }

    /**
     * 生成验证码
     * 
     * @return
     * @see
     */
    @RequestMapping(value = "/login/validateCode.as")
    public String validateCode()
        throws Exception
    {
        return "login/validatecode";
    }

    /**
     * 获得当前菜单的所有子按钮 
     * //TOOD 此方法是否需要被filter拦截?? buttons.do ??
     */
    //@RequestMapping(value = "/control/buttons.do")
    @RequestMapping(value = "/control/buttons.as")
    @ResponseBody
    public List<String> controlButtons(HttpServletRequest request)
        throws Exception
    {
        // 获得当前用户
        String loginName = (String)request.getSession().getAttribute(
            GlobalConstant.AUTH_SESSION_USERNAME_KEY);

        // 获得当前菜单的所有子按钮 用于控制当前页面子按钮的显示与否
        List<String> curButtons = systemService.queryButtonsOfFunc(loginName,
            request.getParameter("funcUrl"));

        return curButtons;
    }

    /**
     * 退出方法 跳转到登录页面
     * 
     * @return
     * @see
     */
    @RequestMapping(value = "login/exit.as")
    public String exit(HttpServletRequest request)
        throws Exception
    {
        // 清空当前session
        request.getSession().invalidate();

        return "login/user_login";
    }

    /**
     * http无操作权限
     * 
     * @return
     * @see
     */
    @RequestMapping(value = "error/noLimit.as")
    public String noLimit()
        throws Exception
    {
        return "error/noLimit";
    }

    /**
     * http session过期
     * 
     * @return
     * @see
     */
    @RequestMapping(value = "error/sessionTimeOut.as")
    public String sessionTimeOut()
        throws Exception
    {
        return "error/sessionTimeOut";
    }

}
